package com.woniu.user.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.ExceptionCode;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.woniu.user.domain.Customer;
import com.woniu.user.domain.RegisterCustomer;
import com.woniu.user.mapper.CustomerMapper;
import com.woniu.user.service.ICustomerService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 外部用户信息Service业务层处理
 * 
 * @author yy
 * @date 2023-04-03
 */
@Service
public class CustomerServiceImpl implements ICustomerService 
{
    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 查询外部用户信息
     * 
     * @param customerId 外部用户信息主键
     * @return 外部用户信息
     */
    @Override
    public Customer selectCustomerByCustomerId(Long customerId)
    {
        return customerMapper.selectCustomerByCustomerId(customerId);
    }

    /**
     * 查询外部用户信息列表
     * 
     * @param customer 外部用户信息
     * @return 外部用户信息
     */
    @Override
    public List<Customer> selectCustomerList(Customer customer)
    {
        return customerMapper.selectCustomerList(customer);
    }

    /**
     * 新增外部用户信息
     * 
     * @param customer 外部用户信息
     * @return 结果
     */
    @Override
    public int insertCustomer(Customer customer)
    {
        return customerMapper.insertCustomer(customer);
    }

    /**
     * 修改外部用户信息
     * 
     * @param customer 外部用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateCustomer(Customer customer)
    {
        return customerMapper.updateCustomer(customer);
    }

    /**
     * 批量删除外部用户信息
     * 
     * @param customerIds 需要删除的外部用户信息主键
     * @return 结果
     */
    @Override
    public int deleteCustomerByCustomerIds(Long[] customerIds)
    {
        return customerMapper.deleteCustomerByCustomerIds(customerIds);
    }

    /**
     * 删除外部用户信息信息
     * 
     * @param customerId 外部用户信息主键
     * @return 结果
     */
    @Override
    public int deleteCustomerByCustomerId(Long customerId)
    {
        return customerMapper.deleteCustomerByCustomerId(customerId);
    }

    @Override
    public Customer selectCustomerByAccountAndPass(String customerAccount, String customerPassword) {
        customerPassword = Md5Utils.hash(Md5Utils.hash(customerPassword));
        return customerMapper.selectCustomerByAccountAndPass(customerAccount,customerPassword);
    }

    @Override
    public String queryWebCode(String phone) {

        //查询手机号是否已经注册过!
        Customer customer = customerMapper.queryCustomerByPhone(phone);
        if (customer != null){
            throw new CustomException(ExceptionCode.USER_ACCOUNT_IN_USE);
        }

        //检查用户手机在24小时内的申请次数
        Long count = redisTemplate.opsForValue().increment("user_register_count_"+phone);

        if (count > 3){
            redisTemplate.expire("user_register_count_"+phone,24, TimeUnit.HOURS);
            throw new CustomException(ExceptionCode.APPLY_TIMES_EXCEPT_LIMIT);
        }

        //生成验证码
        long timeMillis = System.currentTimeMillis();
        String code = (timeMillis + "").substring(9);
        Map<String,String> map = new HashMap();
        map.put("phone",phone);
        map.put("verifyCode",code);

        //把生成的验证码放入redis，有效期是5分钟
        redisCache.setCacheObject("user_register_phone_code_"+phone,code,5, TimeUnit.MINUTES);

        //发送到mq
        rabbitTemplate.convertAndSend("register_exchange","register_routing",map);

        return code;
    }

    @Override
    public void webRegister(RegisterCustomer registerCustomer) {
        //查询手机号是否已经注册过!
        Customer customer = customerMapper.queryCustomerByPhone(registerCustomer.getCustomerAccount());
        if (customer != null){
            throw new CustomException(ExceptionCode.USER_ACCOUNT_IN_USE);
        }

        //检查验证码是否正确
        String code = (String)redisCache.getCacheObject("user_register_phone_code_" + registerCustomer.getCustomerAccount());
        if(!Objects.equals(code,registerCustomer.getVerifyCode())){
            throw new CustomException(ExceptionCode.INVALID_KAPTCHA);
        }

        //检查两次密码是否一致
        if (!registerCustomer.getCustomerPassword().equals(registerCustomer.getConfirmPassword())){
            throw new CustomException(ExceptionCode.SAME_PASSWORD);
        }

        //添加新用户
        Customer newCustomer = new Customer();
        newCustomer.setCustomerName("新用户");
        newCustomer.setCustomerAccount(registerCustomer.getCustomerAccount());

        //密码两次加密
        String hash = Md5Utils.hash(Md5Utils.hash(registerCustomer.getCustomerPassword()));
        newCustomer.setCustomerPassword(hash);

        newCustomer.setCustomerEmail(registerCustomer.getCustomerEmail());
        newCustomer.setCustomerType(2l);/** 用户类型1-管理员 2-普通外部用户 */
        newCustomer.setCustomerStatus(1l);/** 1-有效 2-无效 3-锁定 */
        newCustomer.setCustomerPhone(registerCustomer.getCustomerAccount());
        newCustomer.setCustomerGender("1");/** 性别 '1’-男 '0'-女 */
        newCustomer.setCustomerBirthday(new Date());
        newCustomer.setCustomerAutograph("我还有没有简介哦~");
        newCustomer.setCustomerPoints(0l);
        newCustomer.setCustomerPhoto("https://pics2.baidu.com/feed/d01373f082025aaf1ffa1bcc756ffc6c024f1a73.jpeg?token=5b3a579cd9ed9eb59559f5cf1d93df49");
        newCustomer.setNewCustomerCouponUsed(1l);/** 1-未使用过新人优惠券 2-已经使用过新人优惠券 */

        customerMapper.insertCustomer(newCustomer);
    }

    @Override
    public int uploadWebUser(Customer customer) {
        Customer updateCus = selectCustomerByCustomerId(customer.getCustomerId());
        updateCus.setCustomerName(customer.getCustomerName());
        updateCus.setCustomerPhone(customer.getCustomerPhone());
        updateCus.setCustomerEmail(customer.getCustomerEmail());
        updateCus.setCustomerGender(customer.getCustomerGender());
        updateCus.setCustomerAutograph(customer.getCustomerAutograph());
        updateCus.setCustomerBirthday(customer.getCustomerBirthday());
        updateCus.setCustomerPhoto(customer.getCustomerPhoto());

        int i = updateCustomer(updateCus);

        return i;
    }

    @Override
    public void lockTbCustomer(Integer customerId) {
        customerMapper.lockTbCustomer(customerId);
    }

    @Override
    public void lockTbCustomerTwo(Integer customerId) {
        customerMapper.lockTbCustomerTwo(customerId);
    }

    @Override
    public void resumeCustomer(Integer customerId) {
        customerMapper.resumeCustomer(customerId);
    }


}
